<script setup>
import {onMounted, reactive, ref} from 'vue'
import {PlusOutlined, EditOutlined, RestOutlined, SearchOutlined} from '@ant-design/icons-vue';
import WorkPerformanceAddEdit from "@/views/workPerformance/workPerformanceAddEdit.vue";
import dayjs from "dayjs";
import axios from "axios";
import GlobalParas from "@/GlobalParas.js";
import KingFile from "@/components/KingFile.vue";
import {message} from "ant-design-vue";
import {decrypt} from "@/util/StringOper.js";

let perforArr = ref([])

let perObj = reactive({})

let isOpenWin = ref(false);

let winOpenType = ref("add")

let comKey = ref('a')

let calDurationArr = ref([]);
let calDuration = ref('')

function winOpen(quantifyObj, openType) {
  comKey.value += '1'
  winOpenType.value = openType;
  Object.assign(perObj, quantifyObj);
  isOpenWin.value = true;
}

let queryTimeStart = "";
let queryTimeEnd = "";

onMounted(function () {
  getCalcDuraction().then(res=>{
    queryTimeStart = dayjs(res.timeStart).format("YYYY-MM-DD").toString();
    queryTimeEnd = dayjs(res.timeEnd).format("YYYY-MM-DD").toString();
    getData();
  })
})

async function getCalcDuraction() {
  // console.log("aaaaa")
  return await axios.post(GlobalParas.postUrl + "/calcDuration/getAllCalcDuration", {}).then((res) => {
    calDurationArr.value = res.data;
    calDuration.value=res.data[0].tableKey;

    return res.data[0]
  })
}


function successHandle() {
  getData();
}

function getData() {
  let url = GlobalParas.postUrl + "/viewWorkPerformance/getWorkPerformanceByTimeDuration";
  let paras = {}
  paras.time_start = queryTimeStart;
  paras.time_end = queryTimeEnd;
  paras.record_user_id = decrypt(localStorage.getItem("userId"));

  axios.post(url, paras, {headers:{"auth": decrypt(localStorage.getItem("userName"))}}).then(res => {
    perforArr.value = []
    // console.log(res.data)
    res.data.forEach((item) => {
      let perfor = {}
      perfor.selectedQuantifyItem = {}
      perfor.users = []
      perfor.fileList = []
      perfor.marks = []

      perfor.tableKey = item.tableKey;
      perfor.finish_time = dayjs(item.finishTime).format("YYYY-MM-DD");
      perfor.quantify_title = item.quantifyTitle;
      perfor.selectedQuantifyItem.tableKey = item.dictQuantifyId;
      perfor.selectedQuantifyItem.quantifyRule = item.quantifyRulePath;
      perfor.selectedQuantifyItem.marks = item.marks;
      perfor.comments = item.comments;

      getFileData(item.tableKey).then(files => {
        files.forEach(item => {
          let fileObj = {}
          fileObj.id = item.tableKey;
          fileObj.workPerformanceId = item.tableKey;
          fileObj.fileName = item.fileName;
          fileObj.name = item.fileName;
          fileObj.serverFileName = item.serverFileName;
          fileObj.response = item.serverFileName.split('_')[0];
          fileObj.url = GlobalParas.downLoadPath + item.serverFileName;
          perfor.fileList.push(fileObj);
        })

        getUsersData(item.tableKey).then(users => {
          // console.log(users);
          users.forEach(user => {
            let userObj = {}
            userObj.tableKey = user.userId;
            userObj.realName = user.realName;
            userObj.marks = user.marks;
            perfor.users.push(userObj);
            perfor.marks.push(user.marks);
          })
          perforArr.value.push(perfor);

        })
      })

      // perforArr.value.sort((a, b) => a.finish_time - b.finish_time);
    })
  })
}

async function getFileData(workPerformanceId) {
  let fileUrl = GlobalParas.postUrl + "/workPerformanceFiles/getFilesById";
  let file_paras = {}
  file_paras.workPerformanceId = workPerformanceId
  // console.log(item)
  return await axios.post(fileUrl, file_paras).then(res => {
    return res.data;
  })
}

async function getUsersData(workPerformanceId) {
  let fileUrl = GlobalParas.postUrl + "/viewWorkPerformanceAllocation/getAllocatdUsersById";
  let file_paras = {}
  file_paras.workPerformanceId = workPerformanceId
  // console.log(item)
  return await axios.post(fileUrl, file_paras).then(res => {
    return res.data;
  })
}

function delHandle(eventObj, rowObj) {
  let url = GlobalParas.postUrl + "/workPerformance/delWorkPerformance";
  let paras = {}
  paras.workPerformanceId = rowObj.tableKey;

  axios.post(url, paras).then(res => {
    if (res.data === "success") {
      message.success("数据已删除");
      getData()
    } else {
      message.error("删除失败，原因：" + res.data);
    }
  })
}

function queryDateChangeHandle(selectedKey){
  let selectedItem = calDurationArr.value.filter(item => {
    return item.tableKey === selectedKey;
  })

  queryTimeStart = dayjs(selectedItem[0].timeStart).format("YYYY-MM-DD").toString();
  queryTimeEnd = dayjs(selectedItem[0].timeEnd).format("YYYY-MM-DD").toString();
  getData();
}
</script>

<template>
  <!--    {{perforArr}}-->
  <div class="rowClass" style="height: 40px; padding: 5px 0 0 5px">
    <a-button style="float:left" type="primary" @click="winOpen({}, 'add')">
      <PlusOutlined/>
      增 加
    </a-button>
    <div style="float:left;width:calc(100% - 120px);text-align: right">
      <a-select v-model:value="calDuration" @change="queryDateChangeHandle">
        <a-select-option v-for="item in calDurationArr" :value="item.tableKey">
          {{ item.calcYear }}统计年度：{{dayjs(item.timeStart).format("YYYY-MM-DD")}} 至 {{dayjs(item.timeEnd).format("YYYY-MM-DD")}}
        </a-select-option>
      </a-select>
<!--      <a-button type="primary">-->
<!--        <SearchOutlined/>-->
<!--        查询-->
<!--      </a-button>-->
    </div>
  </div>
  <a-modal :footer="false" v-model:open="isOpenWin" width="930px" title="增加工作业绩">
    <work-performance-add-edit
        v-model:is-win-open="isOpenWin"
        :performance-obj="perObj"
        :open-type="winOpenType"
        :key="comKey"
        @operSuccess="successHandle"
    ></work-performance-add-edit>
  </a-modal>
  <div v-for="item in perforArr" class="rowClass">
    <div class="infoContainer">
      <div class="titleClass">
        <div>[{{ item.finish_time }}] {{ item.quantify_title }}<span
            class="marks">（{{ item.selectedQuantifyItem.marks }}）</span></div>
      </div>
      <div class="userInfo"> 完成人：
        <span v-for="user in item.users">
          <span v-if="user.realName !== ''">
            {{ user.realName }}<span style="color: #da0a0a">[{{ user.marks }}]</span>
          </span>
        </span>
      </div>
      <div class="dictClass">
        {{ item.selectedQuantifyItem.quantifyRule }}
      </div>
      <div class="commentInfo">
        {{ item.comments }}
      </div>
    </div>

    <div class="btnContainer">
      <a-popconfirm title="删除后不可恢复。是否继续？" ok-text="确定" cancel-text="取消"
                    @confirm="eventObj => delHandle(eventObj, item)">
        <div class="btnClass" style="background: #f00">
          <RestOutlined class="btnIcon"/>
          删除
        </div>
      </a-popconfirm>

      <div class="btnClass" @click="winOpen(item, 'edit')">
        <EditOutlined class="btnIcon"/>
        编辑
      </div>
    </div>

    <div class="imgContainer">
      <KingFile v-for="fileItem in item.fileList" :file="fileItem" class="imgClass"></KingFile>
    </div>
  </div>
</template>

<style scoped>
.rowClass {
  background: #fff;
  height: 120px;
  margin-bottom: 10px;
  padding: 0 0 2px 5px;
  font-family: "宋体", "Times New Roman", Times, serif;
}

.infoContainer div {
  margin-bottom: 10px;
}

.infoContainer {
  float: left;
  width: calc(100% - 425px);
}

.titleClass {
  color: #042d68;
  font-size: 18px;
  float: left;
  font-family: "宋体", "Times New Roman", Times, serif;
  font-weight: 400;
  margin-top: 5px;
}

.titleClass div {
  float: left;
  margin-bottom: 0;
}

.titleClass .marks {
  color: #f00
}

.userInfo {
  font-size: 15px;
  clear: both;
}

.dictClass {
  font-size: 14px;
  color: #000;
  max-height: 15px;
  overflow-y: hidden;
  overflow-x: hidden;
}

.commentInfo {
  color: #7e7d7d;
  font-size: 12px;
  margin-top: -2px;
  max-height: 28px;
  width: 100%;
  overflow-x: hidden;
  float: left;
}

.btnContainer {
  float: right;
  margin-top: 5px;
}


.btnClass {
  width: 70px;
  height: 25px;
  background: #5e9fff;
  font-family: "宋体", Times, serif;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  letter-spacing: 2px;
  cursor: pointer;
  float: right;
  margin-right: 10px;
}

.btnClass .btnIcon {
  margin-right: 5px;
}

.imgContainer {
  margin-top: 15px;
  float: right;
  margin-right: 5px;
  width: 420px
}

.imgContainer .imgClass {
  float: left;
  margin-left: 10px;
}
</style>